define(['zepto', 'sui', 'smCityPicker'], function($){
  return {
    init: function(data) {
      this.productId = data.productId;
      this.addressType = data.addressType;
      this.initCityPicker();
      this.submitFrom();
      this.checkZipCode();
    },
    initCityPicker: function() {
      $("#city-picker").cityPicker({
        toolbarTemplate: '<header class="bar bar-nav">\
        <button class="button button-link pull-right close-picker">确定</button>\
        <h1 class="title">选择收货地址</h1>\
        </header>',
        formatValue: function (picker, value, displayValue){
          var province= value[0],city = value[1], region = value[2];
          $('input[name="province"]').val(province)
          $('input[name="city"]').val(city)
          $('input[name="region"]').val(region)
          return displayValue
        }
      });
    },
    checkZipCode: function() {
      $(document).on("change", "input[name='zipCode']", function() {
        if($(this).val()) {
          $(this).parent(".item-input").append('<span class="clear-val"><i class="iconfont icon-x"></i></span>')
          $(this).parents(".item-content").addClass("active")
        } else {
          $(".clear-val").remove();
          $(".address-info ul > .active").removeClass("active")
        }
      })
      
      $(document).on("click", ".clear-val", function() {
        $("input[name='zipCode']").val('');
        $(this).remove();
        $(".address-info ul > .active").removeClass("active")
      })
    },
    submitFrom: function() {
      var that = this;
      
      $(document).on('click', '.save-address-button', function() {
        processedData = $('form').serializeArray();
        /*processedData.push({'selected': true})*/
        var checkform = that.checkForm();
        if(checkform) {
          
          if(that.addressType == 'product') {
            $.modal({
              title:  '是否设置为收货地址',
              extraClass: 'exchange-modal',
              buttons: [
                {
                  text: '否',
                  onClick: function() {
                    processedData.push({'selected': false})
                    $.showPreloader("表单正在提交中...");
                    $.ajax({
                      type: 'POST',
                      url: window.__CTX__.root + "/credit-mall/products/" + that.productId + "/addresses",
                      data: processedData,
                      success: function(res) {
                        $.hidePreloader();
                        if(res.code == 0) {
                          $.toast(res.message)
                          window.location.href= window.__CTX__.root +  "/credit-mall/products/" + res.data.productId + "/addresses";
                        } else {
                          console.log(res.message)
                          $.toast(res.message)
                          setTimeout("window.location.reload()",1000)
                        }
                        
                      },
                      error: function(res) {
                        $.toast("表单提交失败")
                      }
                    })
                  }
                },
                {
                  text: '是',
                  onClick: function() {
                    processedData.push({'selected': true})
                    $.showPreloader("表单正在提交中...");
                    $.ajax({
                      type: 'post',
                      url: window.__CTX__.root + "/credit-mall/products/" + that.productId + "/addresses",
                      data: processedData,
                      success: function(res) {
                        $.hidePreloader();
                        if(res.code == 0) {
                          $.toast(res.message)
                          window.location.href= window.__CTX__.root + "/credit-mall/products/" + res.data.productId+ "?userAddressId="+ res.data.addressId;
                        } else {
                          $.toast(res.message)
                          window.location.href= window.__CTX__.root + "/credit-mall/products/" + res.data.productId+ "/addesses";
                        }
                        
                      },
                      error: function(res) {
                        $.toast("表单提交失败")
                      }
                    })
                  }
                }
              ]
            })
          } else {
            $.showPreloader("表单正在提交中...");
            $.ajax({
              type: 'POST',
              url: window.__CTX__.root + '/profile/addresses',
              data: processedData,
              success: function(res) {
                $.hidePreloader();
                var res = JSON.parse(res)
                if(res.code == 0) {
                  $.toast(res.message)
                  window.location.href= window.__CTX__.root + "/profile/addresses";
                } else {
                  console.log(res.message)
                  $.toast(res.message)
                  setTimeout("window.location.reload()",1000)
                }
                
              },
              error: function(res) {
                $.toast("表单提交失败")
              }
            })
          }
        }
      })
    },
    checkForm: function() {
      var name    = $("input[name='contactName']").val().trim();
      var phone   = $("input[name='contactPhone']").val().trim();
      var city    = $("input[name='city']").val().trim();
      var address = $("textarea[name='address']").val().trim();
      var zipCode = $("input[name='zipCode']").val().trim();
      console.log($("input[type='checkbox']").prop("checked"))
      if(!name) {
        $.toast("请填写收件人信息")
        return false;
      } else if(!phone || !/^((13)|(15)|(17)|(18))\d{9}$/.test(phone)) {
        $.toast("请填写正确的手机号")
        return false
      } else if (!city) {
        $.toast("请填写地区信息")
        return false
      } else if (!address) {
        $.toast("请填写详细地址")
        return false
      } else if(!zipCode || !/^[0-9][0-9]{5}$/.test(zipCode)) {
        $.toast("请填写并格式正确的邮编号码")
        return false
      }
        
      return true;
    }
  }
})